import React, {useEffect, useRef} from 'react';
import {message} from "antd";

interface CanvasComponentProps {
    byteData: number[];
    checkedPeople: ICheckedPerson[];
    /**
     * 检测区域左上角x坐标
     */
    currentDetectionAreaLeftTopX: number;
    /**
     * 检测区域左上角y坐标
     */
    currentDetectionAreaLeftTopY: number;
    /**
     * 检测区域左下角x坐标
     */
    currentDetectionAreaLeftBottomX: number;
    /**
     * 检测区域左下角y坐标
     */
    currentDetectionAreaLeftBottomY: number;
    /**
     * 检测区域右下角x坐标
     */
    currentDetectionAreaRightBottomX: number;
    /**
     * 检测区域右下角y坐标
     */
    currentDetectionAreaRightBottomY: number;
    /**
     * 检测区域右上角x坐标
     */
    currentDetectionAreaRightTopX: number;
    /**
     * 检测区域右上角y坐标
     */
    currentDetectionAreaRightTopY: number;
    showJsonPoint:boolean
    /**
     * jsonVersion
     */
    jsonVersion:number;

}

const CanvasComponent: React.FC<CanvasComponentProps> = (props) => {
    const canvasContainerRef = useRef<HTMLDivElement>({} as HTMLDivElement);
    const width = 320;
    const height = 180;



    useEffect(() => {
        const canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext('2d');
        if (!ctx) return;
        // 绘制每个像素点
        for (let i = 0; i < props.byteData.length; i++) {
            const x = i % width;
            const y = Math.floor(i / width);
            //转换成无符号整数，原始数据中携带了byte负数
            const grayscale = props.byteData[i] & 0xFF;
            // 设置像素点颜色
            ctx.fillStyle = `rgb(${grayscale}, ${grayscale}, ${grayscale})`;
            // 绘制像素点
            ctx.fillRect(x, y, 1, 1); // 绘制一个像素点
        }

        //绘制检测区域
        ctx.beginPath();
        ctx.moveTo(props.currentDetectionAreaLeftTopX, props.currentDetectionAreaLeftTopY); // 左上角
        // 绘制矩形的四条边
        ctx.lineTo(props.currentDetectionAreaRightTopX, props.currentDetectionAreaRightTopY); // 右上角
        ctx.lineTo(props.currentDetectionAreaRightBottomX, props.currentDetectionAreaRightBottomY); // 右下角
        ctx.lineTo(props.currentDetectionAreaLeftBottomX, props.currentDetectionAreaLeftBottomY); // 左下角
        ctx.lineTo(props.currentDetectionAreaLeftTopX, props.currentDetectionAreaLeftTopY); // 回到起点，闭合路径
        // 设置线条样式
        ctx.strokeStyle = 'blue';
        ctx.lineWidth = 0.8;
        // 绘制路径
        ctx.stroke();

        const drawWarehousePositions =  () => {
            try {
                 const configString = localStorage.getItem("config");
                 // 检查configString是否为null，如果不是null，则解析它；如果是null，则使用默认值（例如空对象）
                 const config = configString ? JSON.parse(configString) :'null';
                 if (config=='null'){
                     message.error('未检测到库位json配置，请点击logo进行配置').then();
                     return;
                 }
                Object.values(config).forEach((position: any) => {
                    ctx.fillStyle = 'yellow'; // 设置点位颜色
                    ctx.beginPath();
                    ctx.arc(position.x, position.y, 2, 0, 2 * Math.PI); // 绘制圆形表示点位
                    // ctx.fillText(position.x+","+position.y, position.x, position.y- 10)
                    ctx.fill();
                });
            } catch (error) {
                console.error('Failed to load config.json:', error);
            }
        };
            if (props.showJsonPoint){
                drawWarehousePositions()
            }

        //绘制人头框和编号
        props.checkedPeople.forEach((person) => {
            // 绘制人头框
            ctx.strokeStyle = 'green';
            ctx.strokeRect(person.headX, person.headY, 15, 15);
            // 在人框上绘制人头编号
            ctx.fillStyle = 'red';
            ctx.fillText(person.headNum.toString(), person.headX, person.headY);
            ctx.fillText(person.headX+","+person.headY, person.headX, person.headY- 10)
        });


        // 清空容器并添加新的canvas
        const canvasContainer = canvasContainerRef.current;
        if (canvasContainer) {
            canvasContainer.innerHTML = '';
            canvasContainer.appendChild(canvas);
        }
    }, [props.checkedPeople, props.byteData,props.showJsonPoint,props.jsonVersion]);

    return <div ref={canvasContainerRef} style={{transform: 'scale(3.6)'}}></div>;
};

export default CanvasComponent;
